package com.xbb.monitor.service;

import com.xbb.monitor.entity.MemInfo;
import com.xbb.monitor.entity.echarts.AreaStyle;
import com.xbb.monitor.entity.echarts.LineBean;
import com.xbb.monitor.entity.echarts.Normal;
import com.xbb.monitor.repository.MemInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class MemInfoService {
    @Autowired
    private MemInfoRepository memInfoRepository;
    @PersistenceContext
    private EntityManager entityManager;

    public List<LineBean> getData(Calendar calendar,int interval,SimpleDateFormat sdf){

        String sql = "SELECT id, total, free, buff, cached, used, actual_used, time FROM (\n" +
                "  SELECT b.*,@rownum \\:= @rownum + 1 AS rownum,\n" +
                "  @ptime2 \\:=b.time as ptime2,\n" +
                "  if(TIMESTAMPDIFF(MINUTE,@ptime,b.time)<?2,@ptime=null,@ptime\\:=@ptime2) AS ptime FROM\n" +
                "(SELECT * FROM t_meminfo WHERE TIME >= ?1  ORDER BY time) b,\n" +
                "(SELECT @rownum \\:= 0,@ptime\\:= NULL ,@rank\\:=0,@ptime2\\:=NULL ) a\n" +
                ") AS c WHERE ptime IS NOT NULL";

        Query query = entityManager.createNativeQuery(sql,MemInfo.class);

        query.setParameter(1,calendar.getTime());
        query.setParameter(2,interval);
        List<MemInfo> memInfos = query.getResultList();

        List<LineBean> lineBeans = new ArrayList<LineBean>();
        AreaStyle areaStyle = new AreaStyle(new Normal());
        LineBean lineUsed = new LineBean("used","line","memInfo",areaStyle);
        LineBean lineFree = new LineBean("free","line","memInfo",areaStyle);
        List<String[]> datasUsed = new ArrayList<String[]>();
        List<String[]> datasFree = new ArrayList<String[]>();

        for(MemInfo memInfo : memInfos){
            String[] dataUsed = {sdf.format(memInfo.getTime()),memInfo.getUsed()/1024+""};
            String[] dataFree = {sdf.format(memInfo.getTime()),memInfo.getFree()/1024+""};
            datasUsed.add(dataUsed);
            datasFree.add(dataFree);
        }

        lineUsed.setData(datasUsed);
        lineFree.setData(datasFree);
        lineBeans.add(lineUsed);
        lineBeans.add(lineFree);

        return lineBeans;
    }
}
